package com.ygqh.baby.service.impl;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.handler.ProductPushHandler;
import com.ygqh.baby.kids.entity.bo.KidsProductExt;
import com.ygqh.baby.mapper.YgProductMapper;
import com.ygqh.baby.mapper.YgSkuMapper;
import com.ygqh.baby.model.*;
import com.ygqh.baby.model.wdt.qyb.WdtGoosSpecPushReq;
import com.ygqh.baby.po.*;
import com.ygqh.baby.po.YgProductExample.Criteria;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.wdtqyb.api.WdtQybApi;
import com.ygqh.baby.service.wdtqyb.exception.WdtException;
import com.ygqh.baby.solr.ProductSolrApi;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class YgProductServiceImpl extends AbstractService implements YgProductService {

    static final Integer MAX_PUBLISH_COUNT = 10;


    @Autowired
    private YgProductMapper ygProductMapper;
    @Autowired
    private YgSkuMapper ygSkuMapper;
    @Autowired
    private YgProductImagesService ygImagaService;

    @Autowired
    private YgSkuService ygSkuService;
    @Autowired
    private YgStockService ygStockService;
    @Autowired
    private YgProductPackService packService;
    @Autowired
    private YgCategoryService categoryService;
    @Autowired
    private YgGroupService ygGroupService;
    @Autowired
    private KsdStockService ksdStockService;
    @Autowired
    private YgBmdismService ygBmdismService;
    @Autowired
    private WdtQybApi wdtQybApi;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private YgPreSaleLogsService ygPreSaleLogsService;
    @Autowired
    private RedisCacheEvictService redisCacheEvictService;
    @Autowired
    private ProductSolrApi productSolrApi;
    @Autowired
    private AdminSkuService adminSkuService;
    @Autowired
    private YgSkuMaterialService ygSkuMaterialService;
    @Value("${group_id}")
    private Long groupId;
    @Value("${group_code}")
    private Long groupCode;
    @Autowired
    private YgSupplierService ygSupplierService;
    @Autowired
    private ProductPushHandler productPushHandler;

    @Override
    public List<YgProduct> find(QueryInfo queryInfo, String productName, Long groupId, String productStatus, Long supplierId, Boolean isPreDate) {
        return this.selectProductList(queryInfo, productName, groupId, productStatus, 1L, null, null, false, null, null, true);
    }

    @Override
    public int findCount() {
        YgProductExample example = new YgProductExample();
        example.createCriteria().andStatusNotEqualTo(DataStatus.Delete.name());
        return ygProductMapper.countByExample(example);
    }

    @Override
    public YgProduct findById(Long id) {
        return ygProductMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<YgProduct> findByIds(Long[] ids) {
        YgProductExample example = new YgProductExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andIdIn(Arrays.asList(ids));

        return ygProductMapper.selectByExample(example);
    }

    @Override
    public int save(YgProduct ygProduct) {
        Assert.notNull(ygProduct);
        int r = ygProductMapper.insertSelective(ygProduct);
        addImgSkus(ygProduct);
        return r;
    }

    @Override
    public int update(YgProduct ygProduct) {

        ygImagaService.deleteSoftByProductId(ygProduct.getId());

        if (ygProduct.getProductImages() != null && ygProduct.getProductImages().size() > 0) {
            List<YgProductImages> images = ygProduct.getProductImages();
            for (YgProductImages img : images) {

                img.setId(null);
                img.setProductId(ygProduct.getId());
                ygImagaService.save(img);
            }
        }

        if (ygProduct.getYgSkus() != null && ygProduct.getYgSkus().size() > 0) {
            List<YgSku> skus = ygProduct.getYgSkus();
            //获取当前商品ID下 原来的 有效SKU数据
            List<YgSku> oldSkus = ygSkuService.find(ygProduct.getId());

            int i = 0;
            for (YgSku sku : skus) {
                String outSkuCode = sku.getSkuCode();
                if (sku.getId() == null) {
                    //判断当前SKUCODE 是否已经存在
                    if (oldSkus.stream().filter(m -> m.getSkuCode().equals(sku.getSkuCode())).count() == 1)
                        continue;

                    i++;
                    sku.setProductId(ygProduct.getId());
                    sku.setCreateBy(ygProduct.getUpdateBy());
                    sku.setCreateTime(new Date());
                    sku.getStock().setCreateTime(new Date());
                    //只有商家发货的商品存在此情况
                    if (ygProduct.getSendType().equals(SendType.SupplierSend)) {
                        //获取产品编码的最大skuCode
                        Long skuCode = ygSkuService.findMaxSkuCode(ygProduct.getProductCode());
                        sku.setSkuCode((skuCode + i) + "");
                    }
                    ygSkuService.save(sku);
                    /*
                     * if (ygProduct.getSupplierId() != 1) { updateKsdStock(sku,
                     * ygProduct.getSupplierId()); } else {
                     */
                    YgStock ys = ygStockService.findBySkuCode(sku.getSkuCode());
                    if (ys == null) {
                        YgStock stock = sku.getStock();
                        stock.setSkuCode(sku.getSkuCode());
                        if (ygProduct.getSupplierId() != 1)
                            stock.setIsSync(false);
                        stock.setProductCode(ygProduct.getProductCode());
                        ygStockService.save(stock);
                        //更新 admin_sku
                        //商家为壹果的不用写admin_sku
                        if (ygProduct.getSendType().equals(SendType.SupplierSend)) {
                            AdminSku adminSku = new AdminSku();
                            adminSku.setSkuCode(sku.getSkuCode());
                            adminSku.setGroupId(groupId);
                            adminSku.setProductCode(ygProduct.getProductCode());
                            adminSku.setProductName(ygProduct.getProductName());
                            adminSku.setColor(ygProduct.getShortName());
                            adminSku.setSizeName(sku.getSizeName());
                            adminSku.setCreateTime(new Date());
                            adminSku.setCreateBy(ygProduct.getCreateBy());
                            adminSku.setStatus(DataStatus.Valid);
                            adminSku.setIsCoats(false);
                            adminSku.setOutSkuCode(outSkuCode);
                            adminSkuService.save(adminSku);
                        }


                    } else {
                        sku.getStock().setUpdateTime(new Date());
                        ygStockService.update(sku.getStock());
                    }
                    // }
                } else {
                    if (sku.getStatus().equals(DataStatus.Delete)) {
                        ygSkuService.deleteSoft(sku.getId());
                    } else {
                        sku.setUpdateBy(ygProduct.getUpdateBy());
                        sku.setUpdateTime(new Date());
                        ygSkuService.update(sku);
                        /*
                         * if (ygProduct.getSupplierId() != 1) {
                         * updateKsdStock(sku, ygProduct.getSupplierId()); }
                         * else {
                         */
                        ygStockService.update(sku.getStock());
                        // }
                    }
                }
            }
        }
        ygProductMapper.updateByPrimaryKeySelective(ygProduct);
        if (ygSupplierService.isSyncWDT(ygProduct.getSupplierId())) {
            product_sync(ygProduct.getYgSkus(), ygProduct);
        }
        return 1;
    }

    @Override
    public int updateProductStatus(YgProduct ygProduct) {
        ygProductMapper.updateByPrimaryKeySelective(ygProduct);
        setActionSkuIds();
        return 1;
    }

    private void addImgSkus(YgProduct ygProduct) {
        if (ygProduct.getProductImages() != null && ygProduct.getProductImages().size() > 0) {
            List<YgProductImages> images = ygProduct.getProductImages();
            for (YgProductImages img : images) {
                img.setProductId(ygProduct.getId());
            }
            ygImagaService.saveBatch(images);
        }
        if (ygProduct.getYgSkus() != null && ygProduct.getYgSkus().size() > 0) {
            List<YgSku> skus = ygProduct.getYgSkus();

            for (YgSku sku : skus) {
                sku.setProductId(ygProduct.getId());
                sku.setCreateBy(ygProduct.getCreateBy());
                sku.setCreateTime(ygProduct.getCreateTime());
                sku.getStock().setCreateTime(ygProduct.getCreateTime());
                sku.setNewCustomPrice(ygProduct.getNewCustomPrice());

                /*
                 * if (ygProduct.getSupplierId() != 1) { updateKsdStock(sku,
                 * ygProduct.getSupplierId()); } else {
                 */
                if (ygStockService.findBySkuCode(sku.getSkuCode()) == null) {
                    YgStock stock = sku.getStock();
                    stock.setSkuCode(sku.getSkuCode());
                    if (ygProduct.getSupplierId() != 1)
                        stock.setIsSync(false);
                    stock.setProductCode(ygProduct.getProductCode());
                    ygStockService.save(stock);
                }
                // }
            }
            ygSkuService.saveBatch(skus);
            if (ygSupplierService.isSyncWDT(ygProduct.getSupplierId())) {
                product_sync(ygProduct.getYgSkus(), ygProduct);
            }
        }
    }

    private void product_sync(List<YgSku> skus, YgProduct product) {
        List<WdtGoosSpecPushReq> list = new ArrayList<WdtGoosSpecPushReq>();
        for (YgSku sku : skus) {
            WdtGoosSpecPushReq good = new WdtGoosSpecPushReq(1, product.getProductCode(), sku.getSkuCode(), product.getProductName(),
                    product.getShortName() + " " + sku.getSizeName());

            list.add(good);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    wdtQybApi.goodsSpecPush(list);
                    if (product.getPromotionType().equals(PromotionType.Action))
                        setActionSkuIds();
                } catch (WdtException e) {

                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void delImgSkus(YgProduct ygProduct) {
        YgProduct originalProduct = this.findDetailById(ygProduct.getId());
        Assert.notNull(originalProduct);
        List<YgSku> originalSkus = originalProduct.getYgSkus();
        List<YgProductImages> originalproductImages = originalProduct.getProductImages();
        if (!CollectionUtils.isEmpty(ygProduct.getYgSkus()) && !CollectionUtils.isEmpty(originalSkus)) {
            for (YgSku os : originalSkus) {
                ygSkuService.deleteSoft(os.getId());
                ygStockService.deleteSoft(os.getStockId());
            }
        }

        if (!CollectionUtils.isEmpty(ygProduct.getProductImages()) && !CollectionUtils.isEmpty(originalproductImages)) {
            for (YgProductImages om : originalproductImages) {
                ygImagaService.deleteSoft(om.getId());
            }
        }
    }

    @Override
    public ResultSet<Map<String, Object>> search(QueryInfo queryInfo, String productName, String groupName,
                                                 String productStatus, String supplierName, Boolean isSpecial,
                                                 String productCode, Boolean isGroup, Boolean preSaleDate,
                                                 SalesPlatform salesPlatform) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        ResultSet<Map<String, Object>> resultSet = new ResultSet<Map<String, Object>>(0, list);
        int count = ygProductMapper.countHoutaiProductList(productName, groupName, productStatus, supplierName, isSpecial,
                productCode, isGroup, preSaleDate, salesPlatform);
        if (count > 0) {
            list = ygProductMapper.selectHoutaiProductList(queryInfo, productName, groupName,
                    productStatus, supplierName, isSpecial, productCode, isGroup, preSaleDate, salesPlatform);

            resultSet.setTotal(count);
            resultSet.setResult(list);
        }

        return resultSet;
    }

    @Override
    public List<YgProduct> selectProductList(QueryInfo queryInfo, String productName, Long groupId, String productStatus, Long supplierId, Boolean isSpecial,
                                             String productCode, Boolean isGroup, PromotionType promotionType, BigDecimal vipPrice, Boolean preDate) {
        List<YgProduct> list = ygProductMapper.selectSuper(queryInfo, productName, groupId, productStatus, supplierId, isSpecial, productCode, isGroup,
                promotionType, vipPrice, preDate);
        return list;
    }

    @Override
    public int deleteSoft(Long[] ids) {
        Assert.notEmpty(ids);
        int count = 0;
        for (Long id : ids) {
            YgProduct ygProduct = this.findById(id);
            ygProduct.setStatus(DataStatus.Delete);
            delImgSkus(ygProduct);
            count += ygProductMapper.updateByPrimaryKeySelective(ygProduct);
        }

        return count;
    }

    @Override
    public int deleteSoft(Long id) {
        return this.deleteSoft(new Long[]{id});
    }

    @Override
    public int saveOrUpdate(YgProduct ygProduct) {
        int r = 0;

        if (ygProduct.getPromotionPrice() == null) {
            ygProduct.setPromotionPrice(ZERO);
        }
        if (ygProduct.getId() != null) {
            r = this.update(ygProduct);
        } else {
            saveOtherProduct(ygProduct);
            r = this.save(ygProduct);
        }
        redisCacheEvictService.evictAboutProduct(ygProduct.getId(), null, "product.saveOrUpdate");
        return r;
    }

    private void setPromotionPriceAndVipPrice(YgProduct ygProduct) {
        // 根据款式获取款式是否存在促销价
        YgGroup ygGroup = ygGroupService.findById(ygProduct.getGroupId());
        if (ygGroup.getPromotionPrice() != null && ygGroup.getPromotionPrice().compareTo(ZERO) > 0) {

            if (ygProduct.getPromotionPrice() == null || ygProduct.getPromotionPrice().compareTo(ZERO) == 0) {

                ygProduct.setPromotionPrice(ygGroup.getPromotionPrice());
            }
        }
        BigDecimal shareRate = ygGroup.getShareRate();
        if (shareRate == null || shareRate.compareTo(ZERO) == 0) {
            shareRate = new BigDecimal("0.10");
        }
        // ygProduct.setVipPrice(sharePrice.multiply(ONE.subtract(shareRate)));
        ygProduct.setShareRate(shareRate);
        List<YgSku> ygSkus = ygProduct.getYgSkus();

        for (YgSku sku : ygSkus) {
            sku.setPromotionPrice(ygProduct.getPromotionPrice());

        }


    }

    @Cacheable(cacheNames = "redis", key = "'product:detail_pid_'+#id")
    @Override
    public YgProductModel findDetailModel(Long id) {
        YgProductModel detailModel = ygProductMapper.findDetailModel(id);
        return detailModel;
    }

    @Override
    public YgProductModel findDetailModelV2(Long id) {
        return ygProductMapper.findDetailModelV2(id);
    }

    @Override
    public List<YgProductModel> findDetailModelByGroup(Long groupId) {
        // 查找当前商品所在组的所有商品
        List<YgProductModel> ygProducts = ygProductMapper.findDetailModelByGroup(groupId);
        return ygProducts;
    }

    @Override
    public YgProduct findDetailById(Long id) {
        List<YgProduct> list = findDetailById(id != null ? Collections.singletonList(id) : null);
        return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

    @Override
    public List<YgProduct> findDetailById(List<Long> idList) {
        return ygProductMapper.findDetailById(idList);
    }

    @Override
    public List<YgProduct> findDetailByGroupId(Long id) {
        return ygProductMapper.findDetailByGroupId(id);
    }

    @Override
    public int updateSaleStatus(Long id, ProductStatus status) {
        YgProduct product = this.findDetailById(id);
        List<YgSku> skus = product.getYgSkus();
        boolean flag = false;
        int r = 0;
        for (YgSku sku : skus) {
            long amount = sku.getStock().getAmount();
            if (amount > 0) {
                flag = true;
                break;
            }
        }
        if (flag) {
            product.setSaleStatus(status);
            r = ygProductMapper.updateByPrimaryKey(product);
            redisCacheEvictService.evictAboutProduct(id, null, "product.updateSaleStatus");
            return r;
        } else {
            return r;
        }

    }

    @Override
    public List<Map<String, Object>> findInStockBySkuIds(Long[] skuIds) {
        return ygProductMapper.selectInStockBySkuIds(skuIds);
    }

    @Override
    public List<YgProduct> findGiftByProductCodes(String[] productCodes, PromotionType pType) {

        YgProductExample example = new YgProductExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andProductCodeIn(Arrays.asList(productCodes)).andPromotionTypeEqualTo(pType.name());

        return ygProductMapper.selectByExample(example);
    }

    @Override
    public List<Map<String, Object>> findGiftBySkuIds(Long[] skuIds, PromotionType pType) {
        return ygProductMapper.selectGiftBySkuIds(skuIds, pType);
    }

    @Override
    public List<YgProduct> findByProductCodes(String[] productCodes, PromotionType ordinary) {
        return ygProductMapper.selectByProductCodes(productCodes, ordinary);
    }

    private void setData(List<YgSimilarProductModel> dataBaseList, List<YgSimilarProductModel> result) {
        for (YgSimilarProductModel model : dataBaseList) {
            if (result.size() == MAX_PUBLISH_COUNT)
                return;
            result.add(model);
        }
    }

    @Override
    public List<YgSimilarProductModel> findSimilarityProduct(String brandName, Long categoryId) {
        List<YgSimilarProductModel> step1 = ygProductMapper.findSimilarityProductWidthEqualBrand(brandName, categoryId);
        if (step1.size() >= 10)
            return step1;

        List<YgSimilarProductModel> step2 = ygProductMapper.findSimilarityProductWidthNoEqualBrand(brandName, categoryId);

        setData(step2, step1);
        if (step1.size() >= MAX_PUBLISH_COUNT) {
            return step1;
        }

        return step1;
    }

    @Override
    public Boolean productCodeExist(String productCode, Long productId) {
        YgProductExample example = new YgProductExample();
        Criteria criteria = example.createCriteria();
        criteria.andStatusNotEqualTo(DataStatus.Delete.name()).andProductCodeEqualTo(productCode);
        criteria.andPromotionTypeEqualTo(PromotionType.Ordinary.name());
        if (productId != null) {
            criteria.andIdNotEqualTo(productId);

        }
        int count = ygProductMapper.countByExample(example);

        if (count >= 1) {
            return true;
        }
        return false;
    }

    @Override
    public List<YgProduct> findOrdinaryOnSaleProducts(String name, Long groupId, Long supplierId) {

        return this.findProductList(name, groupId, supplierId, PromotionType.Ordinary, ProductStatus.OnSale);
    }

    @Override
    public List<YgProduct> findProductList(String name, Long groupId, Long supplierId, PromotionType ptype, ProductStatus pStatus) {

        YgProductExample example = new YgProductExample();
        Criteria c = example.createCriteria();

        c.andStatusEqualTo(DataStatus.Valid.name());
        if (groupId != null) {
            c.andGroupIdEqualTo(groupId);
        }
        if (supplierId != null) {
            c.andSupplierIdEqualTo(supplierId);
        }
        if (ptype != null) {
            c.andPromotionTypeEqualTo(ptype.name());
        }
        if (pStatus != null) {
            c.andSaleStatusEqualTo(pStatus.name());
        }
        if (StringUtils.isNotEmpty(name)) {
            c.andProductNameLike("%" + name + "%");
        }
        example.setOrderByClause("create_time desc ");
        return ygProductMapper.selectByExample(example);
    }

    @Override
    public List<YgProduct> findProductForPromotion(QueryInfo queryInfo, String productName, Long groupId, String productStatus, Long supplierId,
                                                   Long promotionId, Boolean isSpecial) {

        List<YgProduct> list = ygProductMapper.selectProductForPromotion(queryInfo, productName, groupId, productStatus, supplierId, promotionId, isSpecial);
        return list;
    }

    @Override
    public List<YgProduct> findProductByPromotionId(QueryInfo queryInfo, Long promotionId) {

        List<YgProduct> list = ygProductMapper.selectProductByPromotionId(queryInfo, promotionId);
        return list;
    }

    @Override
    public int updateSaleStatusByTask(List<Long> ids) {
        return ygProductMapper.updateSaleStatusByTask(ids);
    }

    @Override
    public List<Long> findProductNoStock() {
        return ygProductMapper.selectProductNoStock();
    }

    @Override
    public ResultSet<YgProduct4ShaidanModel> findProduct4ShaidanModel(QueryInfo queryInfo, Long userId) {

        List<YgProduct4ShaidanModel> modelList = ygProductMapper.findProduct4ShaidanModel(queryInfo, userId);
        int count = ygProductMapper.findProduct4ShaidanModelCount(userId);
        ResultSet<YgProduct4ShaidanModel> resultSet = new ResultSet<YgProduct4ShaidanModel>(count, modelList);
        return resultSet;
    }

    @Override
    public ResultSet<YgProduct4ShaidanModel> findProductAllModel(QueryInfo queryInfo) {
        List<YgProduct4ShaidanModel> modelList = ygProductMapper.findProductAllModel(queryInfo);
        int count = ygProductMapper.findProductAllModelCount();
        ResultSet<YgProduct4ShaidanModel> resultSet = new ResultSet<YgProduct4ShaidanModel>(count, modelList);
        return resultSet;
    }

    @Override
    public ResultSet<YgProduct4ListModel> findList(QueryInfo queryInfo, Long[] categoryIds, Boolean isPreProduct, String gender, String productName,
                                                   String tags, Boolean isVip, Long supplierId) {
        List<YgCategory> categorys = categoryService.findByIds(categoryIds);
        // 存放三级id
        List<Long> cids = new ArrayList<>();
        if (categorys != null && categorys.size() > 0) {
            // 存放二级id
            List<Long> ids = new ArrayList<>();
            for (YgCategory category : categorys) {
                if (category.getLevel().equals(Long.valueOf("2"))) {
                    ids.add(category.getId());
                } else {
                    cids.add(category.getId());
                }
            }
            List<YgCategory> categories = categoryService.findByParentIds(ids);
            categories.forEach((cate) -> cids.add(cate.getId()));
        } else {
            if (categoryIds != null)
                cids.addAll(Arrays.asList(categoryIds));
        }

        List<YgProduct4ListModel> modelList = ygProductMapper.findList(queryInfo, ProductStatus.OnSale, null, cids, isPreProduct, gender, productName, tags,
                isVip, supplierId);
        int count = ygProductMapper.findListCount(ProductStatus.OnSale, null, cids, isPreProduct, gender, productName, tags, isVip, supplierId);
        ResultSet<YgProduct4ListModel> resultSet = new ResultSet<>(count, modelList);
        return resultSet;
    }

    @Override
    public ResultSet<YgProduct4ListModel> findListByPack(QueryInfo queryInfo, Long packId) {
        List<YgProduct4ListModel> modelList = findListByPack(queryInfo, packId, SalesPlatform.Yiigoo);
        return new ResultSet<>(1L, modelList);
    }

    @Override
    public List<YgProduct4ListModel> findListByPack(QueryInfo queryInfo, Long packId, SalesPlatform salesPlatform) {
        YgProductPack pack = packService.findValidById(packId);
        if (pack != null && StringUtils.isNotBlank(pack.getProductIds())) {
            List<Long> ids = new ArrayList<>();
            for (String productId : pack.getProductIds().split(",")) {
                ids.add(Long.valueOf(productId));
            }
            queryInfo.setSortKey("product_sale_price");
            return findProduct4ListModelByIds(queryInfo, ids, salesPlatform);
        }
        return null;
    }

    @Override
    public int updateSaleStatus(YgProduct ygProduct) {

        ygProductMapper.updateByPrimaryKeySelective(ygProduct);
        setActionSkuIds();
        redisCacheEvictService.evictAboutProduct(ygProduct.getId(), ygProduct.getProductCode(), "product.updateSaleStatus");
        return 1;
    }

    @Override
    public Boolean IsExistPackByProductId(Long productId) {
        List<YgProduct> list = ygProductMapper.selectProductInPack(productId);
        if (list != null && list.size() > 0)
            return true;
        return false;
    }

    @Override
    public ResultSet<YgHotProductModel> searchHotProduct(HotProductSaleQueryReq queryReq) {
        int count = this.findHotProductCount(queryReq);
        List<YgHotProductModel> list;
        if (count > 0) {

            list = ygProductMapper.findHotProduct(queryReq);
        } else {
            list = Collections.emptyList();
        }
        return new ResultSet<>(count, list);
    }

    @Override
    public List<YgHotProductModel> findHotProductList(HotProductSaleQueryReq queryReq) {
        return ygProductMapper.findHotProduct(queryReq);
    }

    @Override
    public int findHotProductCount(HotProductSaleQueryReq queryReq) {
        return ygProductMapper.findHotProductCount(queryReq);
    }

    @Override
    public int updatePreSaleDate(Long id, Date preSaleDate, String handler) {
        YgProduct ygProduct = this.findById(id);
        ygProduct.setUpdateBy(handler);
        ygProduct.setUpdateTime(new Date());
        ygProduct.setPreSaleDate(preSaleDate);

        ygPreSaleLogsService.addPreSaleLogs(id, preSaleDate, handler, ygProduct.getUpdateTime(), "更新预售日期");
        int i = ygProductMapper.updateByPrimaryKey(ygProduct);

        redisCacheEvictService.evictAboutProduct(id, null, "product.updatePreSaleDate");
        //更新新世界的商品预售
        productPushHandler.pushProductPreDateToOffShop(ygProduct, preSaleDate, OffShop.values());

        return i;
    }

    @Override
    public List<YgProductSaleNumAndCommentNumModel> findSaleNumAndCommentNum() {
        return ygProductMapper.findSaleNumAndCommentNum();
    }

    @Override
    public void updateProductSaleNumAndCommentNum(List<YgProductSaleNumAndCommentNumModel> list) {
        ygProductMapper.updateProductSaleNumAndCommentNum(list);
    }

    @Override
    public void updateWholesalePrice(YgProduct product) {
        ygProductMapper.updateByPrimaryKeySelective(product);
        ygSkuMapper.updateSkuPrice(product.getYgSkus());

    }

    @Override
    public void updateSalesPrice(YgProduct product) {
        boolean diffPrice = ygSkuService.hasDiffPrice(product.getId());
        if (diffPrice) {
            throw new RuntimeException("存在不同价格sku商品，请使用商品编辑功能");
        }
        ygProductMapper.updateByPrimaryKeySelective(product);
        ygSkuService.updateSalesPrice(product.getId(), product.getProductSalePrice(), product.getVipPrice(),
                product.getPromotionPrice(), product.getDistributionPrice());

        redisCacheEvictService.evictAboutProduct(product.getId(), product.getProductCode(), "product.updateSalesPrice");
    }

    @Override
    public int updateSalesStatusByProductCode(YgProduct ygProduct) {
        int i = ygProductMapper.updateSalesStatusByProductCode(ygProduct.getUpdateBy(), ygProduct.getUpdateTime(), ygProduct.getSaleStatus().name(),
                ygProduct.getProductCode(), ygProduct.getSaleTime());
        redisCacheEvictService.evictAboutProduct(ygProduct.getId(), ygProduct.getProductCode(), "product.updateSalesStatusByProductCode");
        return i;
    }

    @Override
    public Message siteSpecial(Long id, Boolean isSpecial) {
        YgProduct product = this.findById(id);
        if (isSpecial) {
//			Boolean isPack = this.IsExistPackByProductId(id);
            StringBuffer strBuf = new StringBuffer();
//			// 特例商品与新客价互斥
//			/*
//			 * if (product.getNewCustomPrice().compareTo(new BigDecimal(0)) > 0)
//			 * { strBuf.append("该商品为新客商品，不能设置为特例商品"); } if
//			 * (!product.getPromotionType().equals(PromotionType.Ordinary)) {
//			 * strBuf.append("该商品为促销活动商品，不能设置为特例商品"); }
//			 */
//			if (isPack) {
//				strBuf.append("该商品为自选包商品，不能设置为特例商品;");
//			}
            List<BmdismModel> list = ygBmdismService.findByProductIds(id);
            if (!CollectionUtils.isEmpty(list)) {
                strBuf.append("该商品为多买多折商品，不能设置为特例商品;");
            }
            if (strBuf.length() > 0) {
                return Message.error(strBuf.toString(), id);
            }
        }
        product.setIsSpecial(isSpecial);
        ygProductMapper.updateByPrimaryKeySelective(product);
        redisCacheEvictService.evictAboutProduct(id, null, "product.siteSpecial");
        return Message.success(id);
    }

    @Override
    public List<String> findAllPreProductSkuCodes() {
        return ygProductMapper.selectAllPreProductSkuCodes();
    }

    @Override
    public void updateCostPrice(YgProduct p) {
        ygSkuMapper.updateCostPrice(p.getYgSkus());

    }

    @Override
    public Long getOrdinaryProductId(Long productId) {
        YgProduct product = this.findById(productId);
        if (product != null && product.getNewCustomPrice().compareTo(new BigDecimal("0")) > 0) {
            YgProduct ygProduct = this.findOrdinaryProductId(product.getProductCode());
            if (ygProduct != null) {
                return ygProduct.getId();
            } else {
                return null;
            }
        }
        return productId;
    }

    private YgProduct findOrdinaryProductId(String productCode) {
        YgProductExample example = new YgProductExample();
        example.createCriteria().andProductCodeEqualTo(productCode).andNewCustomPriceEqualTo(new BigDecimal(0))
                .andPromotionTypeEqualTo(PromotionType.Ordinary.name());
        List<YgProduct> list = ygProductMapper.selectByExample(example);
        if (list != null && list.size() > 0) {

            return list.get(0);
        }
        return null;
    }

    @Override
    public List<YgProduct> findAllProduct(String q, String productStatus, Long groupId, Boolean isSpecial, String productCode, Boolean isGroup,
                                          PromotionType promotionType, Long supplierId) {
        return ygProductMapper.selectProductList(q, productStatus, groupId, isSpecial, productCode, isGroup, promotionType, supplierId);
    }

    @Override
    public void updatePromotionPrice(BigDecimal price, Long groupId, String updateBy, Date updateTime, BigDecimal shareRate, BigDecimal vipRate, BigDecimal distributionPrice) {
        ygProductMapper.updatePromotionPrice(price, groupId, updateBy, updateTime, shareRate, vipRate, distributionPrice);
        redisCacheEvictService.evictProductByGroup(groupId, "product.updatePromotionPrice");
    }

    // 设置活动商品的redis
    private void setActionSkuIds() {

        String skuIds = ygProductMapper.selectActionSkuIds();
        if (StringUtils.isNotEmpty(skuIds))
            redisDao.set("Action_Product", skuIds, 0);

    }

    @Override
    public Map<String, Object> selectProductBySkuId(String skuCode, Long productId) {
        return ygProductMapper.findProductBySkuId(skuCode, productId);
    }

    @Override
    public List<Map<String, Object>> findProductListBySupplierId(Long supplierId) {
        return ygProductMapper.findProductListBySupplierId(supplierId);
    }

    private void updateKsdStock(YgSku sku, Long supplierId) {
        KsdStock stock = new KsdStock();
        stock.setAmount(sku.getStock().getAmount());
        stock.setSkuCode(sku.getSkuCode());
        stock.setSupplierId(supplierId);
        stock.setCreateTime(new Date());
        List<String> skus = new ArrayList<String>();
        skus.add(sku.getSkuCode());
        if (CollectionUtils.isEmpty(ksdStockService.findStockBySkuCode(skus, supplierId)))
            ksdStockService.save(stock);
        else
            ksdStockService.update(stock);

    }

    @Override
    public List<Map<String, Object>> findProductByGroupId(Long supplierId, Long groupId) {

        return ygProductMapper.findProductByGroupId(supplierId, groupId);
    }

    @Override
    public List<YgSkuModel> findSku(Long productId) {

        return ygProductMapper.selectSku(productId);
    }

    @Override
    public ResultSet<YgProduct4ListModel> findListByBmdism(QueryInfo queryInfo, Long bmdismId) {
        List<YgProduct4ListModel> modelList = findListByBmdism(queryInfo, bmdismId, SalesPlatform.Yiigoo);
        return new ResultSet<>(1L, modelList);
    }

    @Override
    public List<YgProduct4ListModel> findListByBmdism(QueryInfo queryInfo, Long bmdismId, SalesPlatform salesPlatform) {
        YgBmdism bmdism = ygBmdismService.findById(bmdismId);
        if (bmdism != null && StringUtils.isNotBlank(bmdism.getProductIds())) {
            List<Long> ids = new ArrayList<>();
            for (String productId : bmdism.getProductIds().split(",")) {
                ids.add(Long.valueOf(productId));
            }
            return findProduct4ListModelByIds(queryInfo, ids, salesPlatform);
        }
        return null;
    }

    @Override
    public List<String> findSkuCodeByproductIds(List<Long> productIds) {
        return ygProductMapper.selectSkuCodeByProductIds(productIds);
    }

    @Override
    public YgProduct findProductById(PromotionType pType, Long productId) {
        return ygProductMapper.findProductById(pType, productId);
    }

    @Override
    public int updateRebate(BigDecimal shareRate, Long supplierId) {
        if (shareRate == null || supplierId == null) {
            return 0;
        }
        return ygProductMapper.updateRebate(shareRate, supplierId);
    }

    @Override
    public List<YgProduct4ListModel> findProduct4ListModelByIds(List<Long> ids) {
        return findProduct4ListModelByIds(null, ids, null);
    }

    @Override
    public List<YgProduct4ListModel> findProduct4ListModelByIds(QueryInfo queryInfo, List<Long> ids,
                                                                SalesPlatform salesPlatform) {
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return ygProductMapper.findProduct4ListModelByIds(queryInfo, ids, salesPlatform);
    }

    @Override
    public void pushToWDT(Long... ids) {
        if (ids != null) {
            List<String> productIds = new ArrayList<>();
            for (Long pid : ids) {
                productIds.add(pid.toString());
            }

            List<YgSkuInfo> skuInfoList = ygSkuService.getSkuInfoList(productIds);

            List<WdtGoosSpecPushReq> goodsList = new ArrayList<>();

            for (YgSkuInfo sku : skuInfoList) {
                WdtGoosSpecPushReq req = new WdtGoosSpecPushReq(2, sku.getProductCode(), sku.getSkuCode(), sku.getProductName(),
                        sku.getShortName() + " " + sku.getSizeName());
                goodsList.add(req);
            }
            try {
                wdtQybApi.goodsSpecPush(goodsList);
            } catch (WdtException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<YgProduct> findBySkuCodes(PromotionType pType, String... skuCodes) {
        return ygProductMapper.selectBySkuCodesV2(pType, skuCodes);
    }

    @Override
    public List<YgProduct> findProductByTime(QueryInfo queryInfo, Date startTime, Date endTime, PromotionType promotionType, ProductStatus productStatus) {
        return ygProductMapper.selectProductByTime(queryInfo, startTime, endTime, promotionType, productStatus);
    }

    @Override
    public int countProductByTime(Date startTime, Date endTime, PromotionType promotionType, ProductStatus productStatus) {
        YgProductExample example = new YgProductExample();
        Criteria criteria = example.createCriteria().andCreateTimeGreaterThanOrEqualTo(startTime).andCreateTimeLessThan(endTime)
                .andStatusEqualTo(DataStatus.Valid.name());
        if (promotionType != null) {
            criteria.andPromotionTypeEqualTo(promotionType.name());
        }
        if (productStatus != null) {
            criteria.andSaleStatusEqualTo(productStatus.name());
        }
        return ygProductMapper.countByExample(example);
    }

    @Override
    public List<YgProduct4ListModel> findProductWithImageByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return ygProductMapper.selectProductWithImageByIds(ids);
    }

    @Override
    public int updateProductNameAndSalePrice(List<YgProduct> productList) {
        if (CollectionUtils.isEmpty(productList)) {
            return 0;
        }
        return ygProductMapper.updateProductNameAndSalePrice(productList);
    }

    @Override
    public int updateShareRateBySupplierId(BigDecimal shareRate, Long supplierId) {
        YgProductExample example = new YgProductExample();
        example.createCriteria().andSupplierIdEqualTo(supplierId).andStatusEqualTo(DataStatus.Valid.name());
        YgProduct record = new YgProduct();
        record.setShareRate(shareRate);
        return ygProductMapper.updateByExampleSelective(record, example);
    }

    @Override
    public ResultSet<YgProduct4ListModel> findOrdinaryProductNotPack(String q, QueryInfo queryInfo, Long packId) {
        List<YgProduct4ListModel> list = ygProductMapper.selectOrdinaryProduct(q, queryInfo, packId);
        int count = ygProductMapper.selectOrdinaryProductCount(q, packId);
        ResultSet<YgProduct4ListModel> resultSet = new ResultSet<YgProduct4ListModel>(count, list);
        return resultSet;
    }

    @Override
    public ResultSet<YgProduct4ListModel> findOrdinaryProduct(String q, QueryInfo queryInfo) {
        List<YgProduct4ListModel> list = ygProductMapper.selectOrdinaryProduct(q, queryInfo, null);
        int count = ygProductMapper.selectOrdinaryProductCount(q, null);
        return new ResultSet<YgProduct4ListModel>(count, list);
    }

    @Override
    public List<Map<String, Object>> findPidAndPcodeBySkuCodes(String... skuCodes) {
        return ygProductMapper.selectPidAndPcodeBySkuCodes(skuCodes);
    }

    @Override
    public List<ProductInfoForSolr> findProductListForSolr(List<Long> productIds) {
        Assert.notEmpty(productIds);
        return ygProductMapper.selectProductListForSolr(productIds);
    }

    @Override
    public ProductInfoForSolr findProductForSolr(Long productId) {
        Assert.notNull(productId);
        List<ProductInfoForSolr> solrList = ygProductMapper.selectProductListForSolr(Collections.singletonList(productId));
        if (CollectionUtils.isEmpty(solrList)) {
            return null;
        }
        return solrList.get(0);
    }

    @Override
    public int updateCategoryAndBasicAttributeByProductCode(Long categoryId, String basicAttribute, List<String> productCodeList) {
        if (CollectionUtils.isEmpty(productCodeList)) {
            return 0;
        }
        String categoryNames = categoryService.findCategoryNameByThirdCategoryId(categoryId);
        int row = ygProductMapper.updateCategoryAndBasicAttributeByProductCode(categoryId, basicAttribute, categoryNames, productCodeList);
        if (row > 0) {
            updateProductSolrByCategoryId(categoryId);
        }
        return row;
    }

    private void updateProductSolrByCategoryId(Long categoryId) {
        new Thread(() -> {
            List<YgProduct> productList = findProductListByCategoryId(categoryId);
            if (CollectionUtils.isEmpty(productList)) {
                return;
            }
            List<Long> idList = productList.stream().map(o -> o.getId()).collect(Collectors.toList());
            productSolrApi.updateProductSolr(idList);
        }).start();
    }

    private List<YgProduct> findProductListByCategoryId(Long categoryId) {
        YgProductExample example = new YgProductExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andCategoryIdEqualTo(categoryId);
        return ygProductMapper.selectByExample(example);
    }

    @Override
    public int updateCategoryNamesByCategoryId(Long categoryId) {
        int row = ygProductMapper.updateCategoryNamesByCategoryId(categoryId);
        if (row > 0) {
            updateProductSolrByCategoryId(categoryId);
        }
        return row;
    }

    @Override
    public List<YgProduct4ListModel> findList(ProductListRequestParam param) {
        List<Long> cids = new ArrayList<>();
        if (param.getCategoryIds() != null && param.getCategoryIds().length > 0) {
            List<YgCategory> categorys = categoryService.findByIds(param.getCategoryIds());
            if (categorys != null && categorys.size() > 0) {
                // 存放二级id
                List<Long> ids = new ArrayList<>();
                for (YgCategory category : categorys) {
                    if (category.getLevel().equals(Long.valueOf("2"))) {
                        ids.add(category.getId());
                    } else {
                        cids.add(category.getId());
                    }
                }
                List<YgCategory> categories = categoryService.findByParentIds(ids);
                categories.forEach((cate) -> cids.add(cate.getId()));
            }
        }
        if (CollectionUtils.isEmpty(cids)) {
            param.setCategoryIds(null);
        } else {
            param.setCategoryIds(cids.toArray(new Long[0]));
        }
        return ygProductMapper.selectByRequestParam(param);
    }

    /**
     * 处理第三方商家产品信息，写admin_sku ,yg_sku_material
     * 此方法只有新增时调用
     *
     * @param ygProduct
     */

    private void saveOtherProduct(YgProduct ygProduct) {
        if (ygProduct.getId() == null && ygProduct.getSendType().equals(SendType.SupplierSend)) {
            //组装admin_sku list
            List<AdminSku> adminSkus = new ArrayList<AdminSku>();
            List<YgSkuMaterial> ygSkuMaterials = new ArrayList<YgSkuMaterial>();
            //获取最大的商品编码
            Long gCode = adminSkuService.findMaxProductCode(groupId);
            String productCode = groupCode + "";
            String skuCode = "";
            if (gCode != null) {
                productCode = (gCode + 1) + "";
            }
            int i = -1;
            String outProductCode = ygProduct.getProductCode();
            ygProduct.setProductCode(productCode);

            for (YgSku sku : ygProduct.getYgSkus()) {
                String outSkuCode = sku.getSkuCode();

                i++;
                //根据skuCode 判断
                AdminSku s = adminSkuService.findOutCodeBySkuCode(outSkuCode);
                if (s != null)
                    continue;
                else {
                    skuCode = productCode + "0" + (i + "");
                    ygProduct.getYgSkus().get(i).setSkuCode(skuCode);
                    AdminSku ad = new AdminSku();
                    ad.setProductCode(productCode);
                    ad.setProductName(ygProduct.getProductName());
                    ad.setColor(ygProduct.getShortName());
                    ad.setSizeName(sku.getSizeName());
                    ad.setSkuCode(skuCode);
                    ad.setGroupId(groupId);
                    ad.setOutProductCode(outProductCode);
                    ad.setOutSkuCode(outSkuCode);
                    ad.setCreateBy(ygProduct.getCreateBy());
                    ad.setCreateTime(new Date());
                    ad.setStatus(DataStatus.Valid);
                    ad.setSalePrice(sku.getSalesPrice());

                    adminSkus.add(ad);

                    YgSkuMaterial ygSkuMaterial = new YgSkuMaterial();
                    ygSkuMaterial.setProductCode(productCode);
                    ygSkuMaterial.setSkuCode(skuCode);
                    ygSkuMaterial.setCostPrice(sku.getCostPrice());
                    ygSkuMaterial.setStatus(DataStatus.Valid);
                    ygSkuMaterial.setCreateBy(ygProduct.getCreateBy());
                    ygSkuMaterial.setCreateTime(new Date());
                    ygSkuMaterial.setBarCode(skuCode);
                    ygSkuMaterials.add(ygSkuMaterial);
                }
            }
            if (adminSkus.size() > 0 && ygSkuMaterials.size() > 0) {
                adminSkuService.saveSkuBatch(adminSkus, ygProduct.getCreateBy());
                ygSkuMaterialService.saveBatchSkuCost(ygSkuMaterials);
            }
        }

    }

    @Cacheable(cacheNames = "redis", key = "'product:yjd_detail_pid_'+#id")
    @Override
    public YgProductModel findDetailModelForYjdian(Long id) {
        YgProductModel product = ygProductMapper.findDetailModelForYjdian(id);
        if (product != null) {
            BigDecimal couponPrice = getCouponPriceForNewCustom(SalesPlatform.Yijiadian);

            BigDecimal price;
            BigDecimal newCustomPrice;
            if (product.getPromotionPrice() != null && product.getPromotionPrice().compareTo(BigDecimal.ZERO) > 0) {
                price = product.getPromotionPrice();
                newCustomPrice = BigDecimal.ZERO;
            } else {
                price = product.getProductSalePrice();
                newCustomPrice = price.compareTo(couponPrice) < 0 ? price : price.subtract(couponPrice);
            }
            BigDecimal sharePrice = price.multiply(product.getShareRate()).setScale(1, BigDecimal.ROUND_HALF_UP);
            product.setSharePrice(sharePrice);
            product.setNewCustomPrice(newCustomPrice);

            product.getSkus().forEach(skuModel -> {
                BigDecimal skuPrice;
                BigDecimal skunNewCustomPrice;
                if (skuModel.getPromotionPrice() != null && skuModel.getPromotionPrice().compareTo(BigDecimal.ZERO) > 0) {
                    skuPrice = skuModel.getPromotionPrice();
                    skunNewCustomPrice = BigDecimal.ZERO;
                } else {
                    skuPrice = skuModel.getSalesPrice();
                    skunNewCustomPrice = skuPrice.compareTo(couponPrice) < 0 ? skuPrice : skuPrice.subtract(couponPrice);
                }
                BigDecimal skuSharePrice = skuPrice.multiply(product.getShareRate()).setScale(1, BigDecimal.ROUND_HALF_UP);
                skuModel.setSharePrice(skuSharePrice);
                skuModel.setNewCustomPrice(skunNewCustomPrice);
            });
        }
        return product;
    }

    @Override
    public Long getSupplierIdByBarcode(String barcode) {
        return ygProductMapper.getSupplierIdByBarcode(barcode);
    }


    @Override
    public Message pushProductInfoToKids(Long productId, String operator, OffShop... offShops) {
        return productPushHandler.pushProductToOffShop(productId, operator, offShops);
    }


    @Override
    public Message batchUpdateProdctName(String searchKey,
                                         String distProductName, String trueName, Date date) {
        ygProductMapper.updateBatchProductName(searchKey, distProductName, trueName, date);
        redisCacheEvictService.evictProductByName(distProductName);
        return SUCCESS_MESSAGE;
    }

    @Override
    public Message batchUpdateProdctByProductIds(String[] productIds,
                                                 String distProductName, String trueName, Date date) {
        ygProductMapper.updateProductNameByProductIds(productIds, distProductName, trueName, date);
        redisCacheEvictService.evictProductByIds(productIds);
        return SUCCESS_MESSAGE;
    }

    @Override
    public List<Map<String, Object>> selectProductListToExport(QueryInfo q,
                                                               String productName, String groupName,
                                                               String productStatus, String supplierName, Boolean special,
                                                               String productCode, Boolean isGroup,
                                                               Boolean preDate, SalesPlatform salesPlatform) {
        return ygProductMapper.selectProductListToExport(q, productName, groupName, productStatus, supplierName, special, productCode, isGroup, preDate, salesPlatform);
    }

    @Override
    public List<YgProduct> findListByName(String distProductName) {
        if (StringUtil.isBlank(distProductName)) {
            return Collections.emptyList();
        }
        YgProductExample example = new YgProductExample();
        example.createCriteria().andPromotionTypeEqualTo(PromotionType.Ordinary.name()).andProductNameLike("%" + distProductName + "%")
                .andStatusEqualTo(DataStatus.Valid.name());
        return ygProductMapper.selectByExample(example);
    }

    @Override
    public int updatePromotionTag(String promotionTag, List<Long> list) {
        int row = 0;
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(list)) {
            row = row + ygProductMapper.updatePromotionTag(promotionTag, list);
        }
        return row;
    }

    @Override
    public List<ProductModelForGroup> productListByGroupOrder(QueryInfo queryInfo, String salesPlatform, String tags,
                                                              boolean skipYg) {
        return ygProductMapper.selectProductByGroupOrder(queryInfo, salesPlatform, tags, skipYg);
    }

    @Override
    public List<YgProduct4ListModel> findListForYjdian(ProductListRequestParam param) {
        param.setSalesPlatform(SalesPlatform.Yijiadian.name());
        List<YgProduct4ListModel> result = this.findList(param);
        processProductPriceForYjdian(result);
        return result;
    }

    @Override
    public void processProductPriceForYjdian(List<YgProduct4ListModel> result) {
        if (!CollectionUtils.isEmpty(result)) {
            BigDecimal couponPrice = getCouponPriceForNewCustom(SalesPlatform.Yijiadian);
            result.forEach(product -> {
                BigDecimal price;
                BigDecimal newCustomPrice;
                if (product.getPromotionPrice() != null && product.getPromotionPrice().compareTo(BigDecimal.ZERO) > 0) {
                    price = product.getPromotionPrice();
                    newCustomPrice = BigDecimal.ZERO;
                } else {
                    price = product.getProductSalePrice();
                    newCustomPrice = price.compareTo(couponPrice) < 0 ? price : price.subtract(couponPrice);
                }
                BigDecimal sharePrice = price.multiply(new BigDecimal(product.getShareRate()))
                        .setScale(1, BigDecimal.ROUND_HALF_UP);
                product.setSharePrice(sharePrice);
                product.setNewCustomPrice(newCustomPrice);
            });
        }
    }

    @Override
    public BigDecimal getCouponPriceForNewCustom(SalesPlatform salesPlatform) {
        String key = String.format(RedisConstant.NEW_CUSTOM_COUPON_PRICE_PREFIX_KEY, salesPlatform);
        String priceValue = redisDao.get(key);
        if (StringUtils.isNotBlank(priceValue)) {
            return new BigDecimal(priceValue);
        }
        return BigDecimal.valueOf(5);
    }

    @Override
    public int countHoutaiProductList(String productName, String groupName,
                                      String productStatus, String supplierName, Boolean isSpecial,
                                      String productCode, Boolean isGroup, Boolean preSaleDate,
                                      SalesPlatform salesPlatform) {

        return ygProductMapper.countHoutaiProductList(productName, groupName, productStatus, supplierName, isSpecial,
                productCode, isGroup, preSaleDate, salesPlatform);
    }

    @Override
    public List<Map<String, Object>> selectHoutaiProductList(QueryInfo queryInfo, String productName, String groupName,
                                                             String productStatus, String supplierName, Boolean isSpecial,
                                                             String productCode, Boolean isGroup, Boolean preSaleDate,
                                                             SalesPlatform salesPlatform) {
        List<Map<String, Object>> list = ygProductMapper.selectHoutaiProductList(queryInfo, productName, groupName,
                productStatus, supplierName, isSpecial, productCode, isGroup, preSaleDate, salesPlatform);
        return list;
    }

    @Override
    public List<YgProduct4ListModel> findListGroupBySecondCategory(ProductListRequestParam param) {
        return ygProductMapper.selectListGroupBySecondCategory(param);
    }

    @Override
    public List<YgProduct4ListModel> findListGroupByProductGroup(ProductListRequestParam param) {
        return ygProductMapper.selectListGroupByProductGroup(param);
    }

    @Override
    public List<Product4SelectListModel> findList4Select(ProductSelectListParam selectListParam) {
        return ygProductMapper.selectList4Select(selectListParam);
    }

    @Override
    public List<YgProduct> findDetailBySaleTime(Date startTime, Date endTime, SalesPlatform salesPlatform) {
        return ygProductMapper.selectDetailBySaleTime(startTime, endTime, salesPlatform);
    }

    @Override
    public List<KidsProductExt> findProductDataByBarCodeForKids(String[] barcodes) {

        if (barcodes == null || barcodes.length == 0) {
            return Collections.emptyList();
        }

        List<Long> pidList = ygProductMapper.selectPidListByBarcode(barcodes);
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(pidList)) {
            return Collections.emptyList();
        }

        return ygProductMapper.selectProductDataByProductIds(pidList);
    }
}
